package com.pray.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.*;

/**
 * RpcServer
 *
 * @author 春江花朝秋月夜
 * @since 2024/1/8 20:42
 */
public class RpcServer {
    private final ExecutorService executorService;
    private final HashMap<String,Object> registeredService;

    public RpcServer() {
        int corePoolSize = 5;
        int maximumPoolSize = 50;
        long keepAliveTime = 60;
        BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<>(100);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        this.executorService =new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,
                TimeUnit.SECONDS,workingQueue,threadFactory);
        this.registeredService = new HashMap<>();
    }
    public void register(Object service){
        registeredService.put(service.getClass().getInterfaces()[0].getName(),service);
    }
    public void serve(int port){
        try {
            ServerSocket serverSocket=new ServerSocket(port);
            System.out.println("server is now in open ");
            Socket handleSocket;
            while ((handleSocket=serverSocket.accept())!=null){
                System.out.println("accepting client of port"+handleSocket.getInetAddress());
                executorService.execute(new RpcServerWorker(handleSocket,registeredService));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
